import 'dart:io';
import 'dart:ui';

import 'package:flutter_logs/flutter_logs.dart';
import 'package:intl/intl.dart';
import 'package:path_provider/path_provider.dart';

///日志输入工具
class LogsUtils {
  static const TAG = "LogsUtils";

  static var now = DateTime.now();
  static DateFormat formatter = DateFormat("yyyy-MM-dd_HH");

  static void loginfo(String tag, String subTag, String info) {
    FlutterLogs.logInfo(tag, subTag, info);
  }

  static void logError(String tag, String subTag, String info) {
    FlutterLogs.logError(tag, subTag, info);
  }

  static void logErrorTrace(String tag, String subTag, String info, Error e) {
    FlutterLogs.logErrorTrace(tag, subTag, info, e);
  }

  static void toFile(info) {
    String logName = formatter.format(now) + '_log';
    FlutterLogs.logToFile(
        logFileName: logName,
        overwrite: false,
        logMessage: info,
        appendTimeStamp: true); //Add time stamp at the end of log message
  }

  static void uploadFile() {
    FlutterLogs.channel.setMethodCallHandler((call) async {
      if (call.method == 'logsExported') {
        var zipName = call.arguments.toString();

        Directory externalDirectory;

        if (Platform.isIOS) {
          externalDirectory = await getApplicationDocumentsDirectory();
        } else {
          externalDirectory = (await getExternalStorageDirectory())!;
        }

        File file = File("${externalDirectory.path}/$zipName");

        if (file.existsSync()) {
          _uploadFile(file);
        } else {
          FlutterLogs.logError(TAG, "existsSync", "File not found in storage.");
        }
      } else if (call.method == 'logsPrinted') {}
    });
  }

  static Future _uploadFile(File file) async {
    FlutterLogs.logInfo(TAG, "existsSync", '上传文件:${file.absolute.path}');
    /*try {} catch (e) {

      logError(TAG, "uploadFile", "catchError:${e.toString()}");
    }*/
  }
}
